<template>
  <div>

    <div style="display: flex; justify-content: center;">
      <el-row type="flex" style="width: 60%;">
        <el-button type="goon" icon="el-icon-back" @click="$router.push('/boss/mytasks/executing')">返回列表</el-button>
      </el-row>
    </div>

    <el-main
        class="detail-box"
        v-loading="loading"
        element-loading-text="正在加载"
        element-loading-spinner="el-icon-loading"
        style="position: relative"
    >

      <InviteWorkers v-if="!isHistoryTask" :taskid="taskId"></InviteWorkers>

      <div class="container-title">
<!--        <img src="../../../../assets/image/task-details.png" alt="" style="width: 150px">-->
        <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
          <el-tab-pane label="任务信息" name="taskInformation">
            <task-detail-table
              :form="form"
            ></task-detail-table>
            <device-requirements-view :value="form.deviceRequirement"></device-requirements-view>
          </el-tab-pane>
          <el-tab-pane label="工人列表" name="workerList">
            <el-descriptions
                class="margin-top"
                :column="1"
                border>
              <el-descriptions-item v-for="worker in workerList">
                <template slot="label">
                  <i class="el-icon-user"></i>
                  工人 {{ worker.workerIndex }}
                </template>
                <el-button type="text" @click="showOneWorker(worker.workerId)">{{ worker.workerName }}</el-button>
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>
        </el-tabs>
        <el-dialog title="工人信息" :visible.sync="workerInfoVisible" width="62%"  center>
                  <span>
                    <el-descriptions :column="3"  border>
                      <el-descriptions-item>
                        <template slot="label">
                          <i class="el-icon-user"></i>
                          用户名
                        </template>
                        {{workerInfoForm.name}}
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          <i class="el-icon-user"></i>
                          擅长技能
                        </template>
                        {{workerInfoForm.skill}}
                      </el-descriptions-item>
                      <el-descriptions-item>
                        <template slot="label">
                          <i class="el-icon-user"></i>
                          任务偏好
                        </template>
                        {{workerInfoForm.favor}}
                      </el-descriptions-item>
                    </el-descriptions>
                    <device-requirements-view :value="form.deviceRequirement"></device-requirements-view>
                    <ActivityForOthers :parentWorkerId="workerInfoForm.workerId" ref="act"></ActivityForOthers>
                    <div class="device-list">
                      <device-card-view v-for="device in workerDeviceList" :key="device.id" :value="device">
                      </device-card-view>
                    </div>
                  </span>
                  <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="workerInfoVisible = false">关闭</el-button>
                  </span>
        </el-dialog>
      </div>

      <div style="margin-top: 20px;">
        <el-button type="goon" style="margin-top: 10px" @click="deleteTask($route.params.taskid)">
          删除任务
        </el-button>

        <el-button id="get-task-btn" type="warning" @click="gotoReportList($route.params.taskid)">
          查看所有报告
        </el-button>
      </div>

    </el-main>

  </div>
</template>

<script>
import ActivityForOthers from "@/components/new/ActiveForOthers";
import { Debounce } from "@/utils/Debounce.js";
import { getTaskDetailsByTaskID, deleteTaskByID} from "@/api/task";
import InviteWorkers from "@/components/boss/release/InviteWorkers";
import {loadWorkerListOfTask, getTaskWorkerDevices} from "@/api/task";
import {loadWorkerInfo} from "@/api/worker";
import DeviceRequirementsView from "@/components/new/device-requirements-card/DeviceRequirementsView";
import DeviceCardView from "@/components/new/device-card/DeviceCardView";
import TaskDetailTable from "@/components/new/task-detail-table/TaskDetailTable";


export default {
  name: 'ExecTaskDetail',
  components: {
    TaskDetailTable,
    DeviceCardView,
    DeviceRequirementsView,
    ActivityForOthers,
    InviteWorkers
  },
  data() {
    return {
      workerDeviceList: [],
      activeName:'taskInformation',
      workerList:[
        // {
        //   workerIndex:1,
        //   workerId:4,
        //   workerName:'长空',
        // },
      ],
      workerInfoVisible:false,
      workerInfoForm:{
        name:'',
        skill:'',
        favor:'',
        workerId:'',
        deviceList:[],
      },


      isHistoryTask: this.$route.query.isHistory === 'true',

      form: {
        id: '',
        taskname: '',
        environment: '',
        deadline: '',
        username: '',
        need_num: '',
        total_num: '',
        description: ''
      },

      taskId: -1
    };
  },

  computed: {
    loading() {
      return this.form['taskname'] === '';
    }
  },

  created() {
    this.getDetailObj();
    this.taskId = this.$route.params.taskid;
  },

  activated() {
    // 触发加载动画
    const tmp = this.form['taskname'];
    this.form['taskname'] = '';

    if (this.$route.params.taskid !== this.taskId) {
      this.getDetailObj();
      this.taskId = this.$route.params.taskid;
    } else {
      this.form['taskname'] = tmp;
    }
  },

  methods: {
    handleClick(){
      console.log('activeName:'+this.activeName)
    },
    showOneWorker(workerId){
      console.log(workerId);

      // todo lyl param name of the List
      // activity和photoUrl好像没用上
      this.loadWorkerInfo(workerId).then(() => {
        this.workerInfoVisible = true;
      }).then(() => {
          this.$refs.act.loadActivityCount(workerId);
      }).catch(err => {
        this.$message.error(err.message);
      });
    },
    // 组件创建后，用于加载任务信息表格
    async getDetailObj() {
      const res = await getTaskDetailsByTaskID(this.$route.params.taskid);
      if (res.code !== 200) {
        return this.$message.error('获取任务信息失败');
      }

      for (let key of Object.keys(res.data)) {
        if (key !== 'type') {
          this.form[key] = res.data[key];
        } else {
          if (res.data['type'] === 'function_test') this.form['type'] = '功能测试';
          else if (res.data['type'] === 'performance_test') this.form['type'] = '性能测试';
          else if (res.data['type'] === 'bug_explore') this.form['type'] = 'Bug探索';
        }
      }
    },


    handleSubmitReport: Debounce(function () {
      const taskid = this.$route.params.taskid;
      this.$router.push(`/worker/mytasks/submitreport/${taskid}`);
    }, 1000),


    gotoReportList(taskID) {
      this.$router.push(`/boss/mytasks/reportlist/${taskID}`)
    },


    async deleteTask(taskid){
      this.$confirm('确定删除任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const res = await deleteTaskByID(taskid);
        if (res.code !== 200) {
          return this.$message.error(res.msg);
        } else {
          this.$message.success('删除成功！');
          await this.$router.push('/admin/plaza');
        }
      }).catch(() => {
      })
    },

    // todo lyl param name of the List
    // req1: 加载特定测试任务的工人列表
    // 接口文档：id, name, photoUrl
    // 前端当前：workerId, workerName, workerIndex
    //    前端为列表形式，没有用到photoUrl
    //    为了列表方便，额外引入了一个 1 to n 的index参数，表明工人数量
    //    index参数可以删，整体不影响页面效果
    loadWorkerList(){
      const taskId = this.$route.params.taskid;
      const userId = sessionStorage.getItem("userid");
      loadWorkerListOfTask({userId:userId,taskId:taskId}).then(res =>{
        console.log(res)
        let index=1;
        for(let item in res.data){
          console.log(item)
          let temp = {};
          temp['workerId']=res.data[item]['id'];
          temp['workerName']=res.data[item]['username'];
          temp['workerIndex']=index;
          index++;
          console.log(temp)
          this.workerList.push(temp)
        }
      })
    },

    loadWorkerInfo(workerId){
      return Promise.all([loadWorkerInfo(workerId).then(res=>{
        console.log(res)
        this.workerInfoForm.workerId = workerId;
        this.workerInfoForm.skill = res.data.skill;
        this.workerInfoForm.favor = res.data.taskPrefer;
        this.workerInfoForm.name = res.data.username
      }), getTaskWorkerDevices(this.$route.params.taskid, workerId).then(res => {
        this.workerDeviceList = res.data;
      })]);
    }
  },
  mounted(){
    this.loadWorkerList();
  }
}
</script>


<style>

.el-descriptions-item__label.is-bordered-label {
  width: 120px !important;
}

</style>

<style scoped>
.device{
  text-align: center;
  border-style: solid;
  border-width: 3px;
}
.el-button {
  margin-top: 10px;
}

.detail-box {
  margin: 10px auto;
  width: 60%;

  border: 1px solid #DCDFE6;
  box-shadow: 0 0 8px #909399;

  padding: 3% 3%;

  background-color: #ffffff;
}
.device-list {
  display: grid;
  grid-template-columns: repeat(
      auto-fill,
      minmax(300px, 1fr)
    );
  grid-gap: 20px;
}

</style>
